package com.suhe.ozon.http;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.suhe.ozon.consts.OzonConsts;
import com.suhe.ozon.entity.dto.OrderDTO;
import com.suhe.ozon.entity.po.ClientPO;
import com.suhe.ozon.entity.po.OrderProductPO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * </p>
 *
 * @author liuning
 * @date 00:12 2024/1/19
 */
@Slf4j
public class OrderHttp {

    /**
     * 获取订单列表URL
     */
    private final static String GET_UNFULFILLED_ORDER_URL = "https://api-seller.ozon.ru/v3/posting/fbs/list";

    /**
     * 订单数据同步
     *
     * @param ozonClient ozon客户端信息
     * @param searchStartTime 检索开始时间
     * @param orderStatus 订单状态
     * @return
     * @throws IOException
     */
    public void sync(ClientPO ozonClient, LocalDateTime searchStartTime, String orderStatus, List<OrderDTO> orderList) throws IOException {
        process(ozonClient, searchStartTime, orderStatus, 0, orderList);
    }

    private void process(ClientPO ozonClient, LocalDateTime searchStartTime, String orderStatus, int page, List<OrderDTO> orderList) throws IOException {
        if (searchStartTime == null) {
            searchStartTime = LocalDateTime.now().minusYears(1); // 如果没有
        }

        final CloseableHttpClient httpClient = HttpClients.createDefault();
        final HttpPost httpPost = new HttpPost(GET_UNFULFILLED_ORDER_URL);
        httpPost.addHeader("Client-Id", ozonClient.getClientId());
        httpPost.addHeader("Api-Key", ozonClient.getSecretKey());
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.addHeader("Host", "api-seller.ozon.ru");

        final ImmutableMap<String, Object> params = ImmutableMap.of("dir", "ASC"
                , "filter", ImmutableMap.of("since", localDateTime2Str(LocalDateTime.now().minusMonths(6)), "to", localDateTime2Str(LocalDateTime.now()))
                , "offset", page
                , "limit", OzonConsts.HTTP_PAGE_LIMIT
        );
        StringEntity stringEntity = new StringEntity(JSONUtil.toJsonStr(params));
        stringEntity.setContentEncoding("UTF-8");
        stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);

        final CloseableHttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            log.error("接口请求失败");
        }
        String result = EntityUtils.toString(response.getEntity());
        final JSONObject jsonObject = JSONUtil.parseObj(result).getJSONObject("result");
        final JSONArray orders = jsonObject.getJSONArray("postings");
        for (int i = 0; i < orders.size(); i++) {
            final JSONObject order = orders.getJSONObject(i);
            String orderNo = order.getStr("order_number"); // 订单号
            LocalDateTime orderTime = order.getLocalDateTime("in_process_at", null); // 下单时间
            String trackingNumber = order.getStr("tracking_number"); // 物流跟踪号
            final JSONArray products = order.getJSONArray("products");
            final OrderDTO orderDTO = new OrderDTO();
            orderDTO.setOrderNo(orderNo);
            orderDTO.setOrderTime(orderTime);
            orderDTO.setTrackingNumber(trackingNumber);
            orderDTO.setClientId(ozonClient.getClientId());
            orderDTO.setOrderStatus(order.getStr("status"));
            for (int j = 0; j < products.size(); j++) {
                final JSONObject product = products.getJSONObject(j);
                final String productName = product.getStr("name"); // 商品名称
                final BigDecimal productPrice = product.getBigDecimal("price"); // 商品价格
                final int productQuantity = product.getInt("quantity"); // 商品数量
                final String productSku = product.getStr("sku"); // 商品sku
                final String productOfferId = product.getStr("offer_id"); // 商品货号
                final String productCurrencyCode = product.getStr("currency_code"); // 价格货币
                final OrderProductPO orderProductPO = new OrderProductPO()
                        .setOrderNo(orderNo)
                        .setProductName(productName)
                        .setProductPrice(productPrice)
                        .setProductQuantity(productQuantity)
                        .setProductSku(productSku)
                        .setProductCurrencyCode(productCurrencyCode);
                orderDTO.getProducts().add(orderProductPO);
                orderDTO.setOrderPrice(orderDTO.getOrderPrice().add(orderProductPO.getProductPrice().multiply(new BigDecimal(orderProductPO.getProductQuantity()))))
                        .setProductQuantity(orderProductPO.getProductQuantity()); // 更新订单中的商品数量和价格
            }
            orderList.add(orderDTO);
        }
        if (jsonObject.getBool("has_next")) {
            process(ozonClient, searchStartTime, orderStatus, ++page, orderList);
        }
    }

    private String localDateTime2Str(LocalDateTime localDateTime) {
        // 创建 ZoneId 对象表示 UTC 时区
        ZoneId utcZone = ZoneOffset.UTC;
        // 将 LocalDateTime 转换为 ZonedDateTime
        ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, utcZone);
        // 输出结果
        return zonedDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssX"));
    }
}
